package com.young.fragments.demo.lazy_show_demo

import android.os.Bundle
import android.view.View
import androidx.fragment.app.Fragment
import androidx.viewpager2.adapter.FragmentStateAdapter
import com.young.fragments.databinding.ActivityLazyShowBinding
import com.young.fragments.demo.lazy_show_demo.fms.LazyShowFragment1
import com.young.fragments.demo.lazy_show_demo.fms.LazyShowFragment2
import com.young.fragments.demo.lazy_show_demo.fms.LazyShowFragment3
import com.young.fragments.demo.lazy_show_demo.fms.LazyShowFragment4
import com.young.lib_fragments.acs.BaseActivity

/**
 * @author huangzehui
 * @date 2025/1/24 12:53 周五
 * @description 懒加载demo
 *
 * androidx.viewpager:viewpager2:1.0.0@aar
 *
 * ViewPager2 使用 FragmentStateAdapter(@NonNull FragmentActivity fragmentActivity) 这个方式的 adapter ，可使用当前的懒加载
 */
class LazyShowActivity : BaseActivity(), View.OnClickListener {

    // binding
    private val mBinding by lazy {
        ActivityLazyShowBinding.inflate(layoutInflater)
    }

    private val mFragmentStateAdapter = object : FragmentStateAdapter(this) {

        override fun getItemCount(): Int {
            return 4
        }

        override fun createFragment(position: Int): Fragment {
            return when (position) {
                0 -> {
                    LazyShowFragment1()
                }

                1 -> {
                    LazyShowFragment2()
                }

                2 -> {
                    LazyShowFragment3()
                }

                3 -> {
                    LazyShowFragment4()
                }

                else -> {
                    throw Exception("no fragment")
                }
            }
        }

    }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(mBinding.root)
        initViewPager()
        initClick()
    }

    override fun getFragmentContainerId(): Int {
        return 0
    }


    private fun initViewPager() {
        mBinding.vpContainer.offscreenPageLimit = 3
        mBinding.vpContainer.adapter = mFragmentStateAdapter
    }

    private fun initClick() {
        mBinding.btnPage1.setOnClickListener(this)
        mBinding.btnPage2.setOnClickListener(this)
        mBinding.btnPage3.setOnClickListener(this)
        mBinding.btnPage4.setOnClickListener(this)
    }

    override fun onClick(v: View?) {
        when (v) {
            mBinding.btnPage1 -> {
                mBinding.vpContainer.currentItem = 0
            }

            mBinding.btnPage2 -> {
                mBinding.vpContainer.currentItem = 1
            }

            mBinding.btnPage3 -> {
                mBinding.vpContainer.currentItem = 2
            }

            mBinding.btnPage4 -> {
                mBinding.vpContainer.currentItem = 3
            }

            else -> {

            }
        }
    }

}